#include "QuickImGui.h"

#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"

QuickImGui::QuickImGui(uint32_t width, uint32_t height, const char* title, bool continuouslyRender) :
    mWindow(nullptr),
    mClearColor(ImColor(.5f, .5f, .5f, .5f)),
    mTitle(title),
    mWindowWidth(width),
    mWindowHeight(height),
    mbContinuouslyRender(continuouslyRender)
{
}
QuickImGui::~QuickImGui() {}

void QuickImGui::glfw_error_callback(int error, const char* description)
{
    fprintf(stderr, "GLFW Error %d: %s\n", error, description);
}

void QuickImGui::initialize() {
    createWindow();
    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls

    updateFrameScale();

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
    // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
    // - Read 'docs/FONTS.md' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details.
    // io.Fonts->AddFontDefault();
    // io.Fonts->AddFontFromFileTTF("C:/Windows/Fonts/msyh.ttc", 16.0f, nullptr, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != nullptr);

    // io.Fonts->AddFontFromFileTTF("C:/Windows/Fonts/msyh.ttc", 16.0f, nullptr, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());

    // Setup Dear ImGui style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsLight();

    // Setup Platform/Renderer backends
    ImGui_ImplGlfw_InitForOpenGL(mWindow, true);
#ifdef __EMSCRIPTEN__
    ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas");
#endif
    const char* glsl_version = "#version 130";
    ImGui_ImplOpenGL3_Init(glsl_version);
}

void QuickImGui::setFrameRenderContent(const std::function<void()>& func) {
    mFrameRenderContent = func;
}

void QuickImGui::setClearColor(ImColor color) {
    mClearColor = color;
}

void QuickImGui::quit() {
    glfwSetWindowShouldClose(mWindow, GL_TRUE);
}

void QuickImGui::finalize() {
    // Cleanup
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();

    glfwDestroyWindow(mWindow);
    glfwTerminate();
}

void QuickImGui::mainLoop() {
    // Main loop
#ifdef __EMSCRIPTEN__
    // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
    // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
    io.IniFilename = nullptr;
    EMSCRIPTEN_MAINLOOP_BEGIN
#else
    while (!glfwWindowShouldClose(mWindow))
#endif
    {
        // Poll and handle events (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.

        if (mbContinuouslyRender) {
            glfwPollEvents();
        }
        else {
            // glfwWaitEvents();
            glfwWaitEventsTimeout(0.1);
            // LOG("Timeout");
        }

        startNewFrame();
        renderFrameContent();
    }
#ifdef __EMSCRIPTEN__
    EMSCRIPTEN_MAINLOOP_END;
#endif
    finalize();
}
// Create GLFWwindow
void QuickImGui::createWindow() {
    glfwSetErrorCallback(glfw_error_callback);
    if (!glfwInit())
    {
        LOG("Error: glfwInit failed!");
        return;
    }

    // Decide GL+GLSL versions
#if defined(IMGUI_IMPL_OPENGL_ES2)
        // GL ES 2.0 + GLSL 100
    const char* glsl_version = "#version 100";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
#elif defined(__APPLE__)
        // GL 3.2 + GLSL 150
    const char* glsl_version = "#version 150";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // Required on Mac
#else
        // GL 3.0 + GLSL 130
    const char* glsl_version = "#version 130";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // 3.0+ only
#endif

        // Create window with graphics context
    mWindow = glfwCreateWindow(mWindowWidth, mWindowHeight, mTitle.c_str(), nullptr, nullptr);
    if (mWindow == nullptr)
    {
        LOG("Error: glfwCreateWindow failed!");
        return;
    }
    glfwMakeContextCurrent(mWindow);
    glfwSwapInterval(1); // Enable vsync
}


// Start the Dear ImGui frame
void QuickImGui::startNewFrame() {
    ImGui_ImplOpenGL3_NewFrame();
    ImGui_ImplGlfw_NewFrame();
    ImGui::NewFrame();
}

// Render frame content
void QuickImGui::renderFrameContent() {
    if (mFrameRenderContent != nullptr) {
        mFrameRenderContent();
    }
    // Rendering
    ImGui::Render();
    int display_w, display_h;
    glfwGetFramebufferSize(mWindow, &display_w, &display_h);

    glViewport(0, 0, display_w, display_h);
    float r = mClearColor.Value.x * mClearColor.Value.w;
    float g = mClearColor.Value.y * mClearColor.Value.w;
    float b = mClearColor.Value.z * mClearColor.Value.w;
    float a = mClearColor.Value.w;
    glClearColor(r, g, b, a);
    glClear(GL_COLOR_BUFFER_BIT);

    // auto* pMonitor = glfwGetPrimaryMonitor();
    // float scale_x, scale_y;
    // glfwGetMonitorContentScale(pMonitor, &scale_x, &scale_y);
    // ImGui::GetDrawData()->FramebufferScale = ImVec2(scale_x, scale_y);

    ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

    glfwSwapBuffers(mWindow);
}

void QuickImGui::updateFrameScale() {
#if 0
    ImGuiIO& io = ImGui::GetIO();
    auto* pMonitor = glfwGetPrimaryMonitor();
    float scale_x, scale_y;
    glfwGetMonitorContentScale(pMonitor, &scale_x, &scale_y);
    // LOG("scale_x = %f", scale_x);
    // LOG("scale_y = %f", scale_y);
    io.DisplayFramebufferScale.x = scale_x;
    io.DisplayFramebufferScale.y = scale_y;
    io.FontGlobalScale = scale_x;
#endif
}
